<?php

namespace magein\laravel\seecms\command;

use Illuminate\Console\Command;

class Vendor extends Command
{
    protected $raw_url = 'https://gitee.com/magein/static-vendor';

    protected $version = 'v1';

    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'seecms:vendor {name="seecms"} {--url=} {--tag=}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '加载静态资源文件';

    protected $help = '
    php artisan seecms:vendor                           安装静态资源文件
    php artisan seecms:vendor --url                     下载地址
    php artisan seecms:vendor --tag                     下载版本标签
';

    public function handle()
    {
        $this->name = trim(trim($this->argument('name')), '/') ?: $this->name;
        $this->raw_url = trim(trim($this->option('url')), '/') ?: $this->raw_url;
        $this->version = trim(trim($this->option('tag')), '/') ?: $this->version;

        if (empty($this->name)) {
            $this->error('目录名称不能为空');
            exit(1);
        }

        if (empty($this->raw_url)) {
            $this->error('下载远程地址不能为空');
            exit(1);
        }

        if (empty($this->version)) {
            $this->error('下载版本不能为空');
            exit(1);
        }

        $target = public_path('vendor');
        if (!is_dir($target)) {
            mkdir($target, 0766, true);
        }

        $this->download($target);

        $this->line('static download completed');
    }

    protected function remoteRawMaster($url): string
    {
        return $this->raw_url . '/raw/master/' . $url;
    }

    protected function lists()
    {
        $data = file_get_contents($this->remoteRawMaster('seecms.v1'));

        if (empty($data)) {
            return [];
        }

        return explode("\n", $data);
    }

    public function download($target)
    {
        $lists = $this->lists();

        if (empty($lists)) {
            return false;
        }

        foreach ($lists as $item) {

            $item = trim($item);
            if (empty($item)) {
                continue;
            }
            //  验证版本
            if (preg_match('/^seecms/', $item) && !preg_match('/' . $this->version . '/', $item)) {
                continue;
            }

            $dir = $target . '/' . pathinfo($item, PATHINFO_DIRNAME);

            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $filepath = $target . '/' . $item;
            if (is_file($filepath)) {
                $this->info("跳过 : $item");
                continue;
            }

            $content = file_get_contents($this->remoteRawMaster($item));

            file_put_contents($filepath, $content);

            if (is_file($filepath)) {
                $this->info("下载 :$item 完成");
            }
        }
    }
}
